import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/api/interface/user_api.dart';
import 'package:sptapp/api/request/response_data.dart';
import 'package:sptapp/moudle/event_bus.dart';
import 'package:sptapp/moudle/message.dart';
import 'package:sptapp/page/min/min_select_device.dart';
import 'package:sptapp/widget/common_widget.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../config/const.dart';
import '../../moudle/common_info.dart';
import '../../moudle/permiss_handler/permission_operate.dart';
import '../../widget/cache_image.dart';
import 'connect_us.dart';

class MinPage extends StatefulWidget {
  const MinPage({super.key});

  @override
  State<MinPage> createState() => _MinPageState();
}

class _MinPageState extends State<MinPage> {

  List _items = [
    {
      'name':min_add_device_text.tr,
      'img':'assets/home/min_add_device.png',
    },
    {
      'name':min_device_net_text.tr,
      'img':'assets/home/min_net_device.png',
    },
    {
      'name':min_connect_us_text.tr,
      'img':'',
    },
    {
      'name':min_set_page_item_version.tr,
      'img':'assets/home/min_info.png',
      'value':'1.0.0'
    },
    {
      'name':"SPT Personnel".tr,
      'img':'assets/home/min_installer_icon.png',
      'value':''
    }
  ];

  Map feedbackInfo= {
    'spt.receive.email':{
      // 'value':'api@sptus.com'
      'value':''
    },
    'spt.phone':{
      // 'value':'800-677-5014'
      'value':''
    },
  };

  late StreamSubscription _subscription;
  late StreamSubscription _devicesubscription;

  bool isMail = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getInfo();
    _getFeedbackInfo();
    _subscription = eventBus.on<UserInfoChange>().listen((val){
      if(mounted){setState(() {});}
    });
    _devicesubscription = eventBus.on<DeviceInfoChange>().listen((val){
      _getInfo();
    });
  }

  _getInfo()async{
    getBaseUserInfo((){
      if(mounted){setState(() {});}
    });
    if(mounted){
      setState(() {});
    }
  }

  _getFeedbackInfo()async{
    ResponseData res = await UserAPI.getFeedbackInfo();
    if(res.code == 200 && res.data != null){
      feedbackInfo = res.data;
      isMail = await canLaunchUrl(Uri.parse('mailto:${feedbackInfo['spt.receive.email']['value']??''}'));
      if(mounted){
        setState(() {});
      }
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _subscription.cancel();
    _devicesubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xff1E1E1E),
        body: GestureDetector(
          onTap: (){

          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 40.w,),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: ScreenUtil().statusBarHeight+20.w,),
                GestureDetector(
                  onTap: (){
                    Navigator.of(context).pushNamed('MinInfoPage');
                  },
                  child: Container(
                    color: Colors.transparent,
                    child: Row(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(96.w),
                          child: CacheImage(
                            image: 'assets/home/home_person.png',
                            width: 96.w,
                            height: 96.w,
                            fit: BoxFit.fitWidth,
                          ),
                        ),
                        SizedBox(width: 24.w,),
                        Expanded(child: Container(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // Text(min_nick_name_text.tr,style: TextStyle(
                              //     color: Colors.white,
                              //     fontSize: 28.sp
                              // ),),
                              Text(baseUserInfo['nickname']??'',style: TextStyle(
                                  color: Color(0xffB3B3B3),
                                  fontSize: 28.sp
                              ),)
                            ],
                          ),
                        )),
                        SizedBox(width: 24.w,),
                        Image.asset('assets/home/min_info_set.png',width: 40.w,)
                      ],
                    ),
                  ),
                ),
                SizedBox(height: 80.w,),
                Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Container(
                          alignment: Alignment.center,
                          child: Column(
                            children: [
                              GestureDetector(
                                onTap: (){
                                  if(baseDevices.isEmpty){
                                    // Navigator.of(context).pushNamed('AddDevicePage');
                                  }else{
                                    showModalBottomSheet(context: context, builder: (ctx){
                                      return MinSelectDeviceDialog(callBack: (){
                                        eventBus.fire(DeviceInfoChange());
                                        setState(() {
                                          if(baseDevice?['status'].toString() == '2'){
                                            // _showNoNetworkAlert();
                                          }
                                        });
                                      },);
                                    },isScrollControlled: true);
                                  }
                                },
                                child:  Container(
                                  child: Image.asset('assets/home/min_spt.png',width: 140.w,fit: BoxFit.fitWidth,),
                                ),
                              ),
                              GestureDetector(
                                onTap: (){
                                  if(baseDevices.isEmpty){
                                    // Navigator.of(context).pushNamed('AddDevicePage');
                                  }else{
                                    showModalBottomSheet(context: context, builder: (ctx){
                                      return MinSelectDeviceDialog(callBack: (){
                                        if(mounted){
                                          setState(() {
                                            if(baseDevice?['status'].toString() == '2'){
                                              // _showNoNetworkAlert();
                                            }
                                          });
                                        }
                                      });
                                    },isScrollControlled: true);
                                  }
                                },

                                child: Container(
                                  child: Column(
                                    children: [
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          Text(baseDevice?['name']??min_no_device_text.tr,style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 28.sp
                                          ),),
                                          SizedBox(width: 10.w,),
                                          Image.asset('assets/home/min_choose_device_down.png',width: 32.w,)
                                        ],
                                      ),
                                      SizedBox(height: 24.w,),
                                      GestureDetector(
                                        onTap: (){
                                          if(baseDevice!=null&& baseDevice?['name'] != null &&baseDevice?['name']!.isNotEmpty){
                                            Navigator.of(context).pushNamed('MinChangeDeviceName', arguments: baseDevice).then((val){
                                              if(val is String && val!=null && val.isNotEmpty){
                                                baseDevice?['name'] = val;
                                              }
                                              setState(() {});
                                            });
                                          }
                                        },
                                        child: Container(
                                          width: 140.w,
                                          height: 40.w,
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                              color: Color(0xff313131),
                                              borderRadius: BorderRadius.circular(40.w)
                                          ),
                                          child: Text('Rename',style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 20.sp
                                          ),),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                        SizedBox(height: 40.w,),
                        Column(
                          children: [
                            itemWidget(0),
                            itemWidget(1),
                          ],
                        )
                        // itemWidget(2),
                      ],

                    )
                ),
                Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        child: Text(connect_us_page_title.tr,style: TextStyle(
                          color: Color(0xffA4A4A4),
                          fontSize: 24.sp
                        ),),
                        height: 44.w,
                      ),
                      SizedBox(height: 8.w,),
                      Container(
                        height: 1.w,
                        color: Color(0x1fffffff),
                      ),
                      SizedBox(height: 32.w,),
                      GestureDetector(
                        onTap: (){
                          SmartDialog.show(builder: (ctx){
                            return connectItem(feedbackInfo['spt.receive.email']['value']??'', 'assets/home/min_emial.png', 2);
                          },alignment: Alignment.center);
                        },
                        child: Container(
                          height: 84.w,
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: 20.w),
                          decoration: BoxDecoration(
                            color: Color(0xff2A2A2A),
                            borderRadius: BorderRadius.circular(8.w)
                          ),
                          child: Row(
                            children: [
                              Image.asset('assets/home/min_emial.png',width: 36.w,),
                              SizedBox(width: 24.w,),
                              Text(feedbackInfo['spt.receive.email']['value']??'',style: TextStyle(
                                color: Colors.white,
                                fontSize: 28.sp
                              ),)
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 24.w,),
                      GestureDetector(
                        onTap: (){
                          SmartDialog.show(builder: (ctx){
                            return connectItem(feedbackInfo['spt.phone']['value']??'', 'assets/home/min_phone.png', 1);
                          },alignment: Alignment.center);
                        },
                        child: Container(
                          height: 84.w,
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(horizontal: 20.w),
                          decoration: BoxDecoration(
                              color: Color(0xff2A2A2A),
                              borderRadius: BorderRadius.circular(8.w)
                          ),
                          child: Row(
                            children: [
                              Image.asset('assets/home/min_phone.png',width: 36.w,),
                              SizedBox(width: 24.w,),
                              Text(feedbackInfo['spt.phone']['value']??'',style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 28.sp
                              ),)
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 32.w,),
                      Container(
                        height: 1.w,
                        color: Color(0x1fffffff),
                      ),
                      SizedBox(height: 32.w,),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
                  child: itemWidget(3),
                )
              ],
            ),
          ),
        )
    );
  }

  itemWidget(int index){
    return GestureDetector(
      onTap: (){
        if(index == 0){
          SmartDialog.show(builder: (ctx){
            return Container(
              height: 530.w,
              padding: EdgeInsets.only(left: 48.w,right: 48.w,top: 32.w,bottom: 48.w),
              decoration: BoxDecoration(
                  color: Color(0xff1E1E1E),
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(32.w),topRight: Radius.circular(32.w))
              ),
              child: Column(
                children: [
                  Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('Add new device',style: TextStyle(
                            color: Colors.white,
                            fontSize: 28.sp,
                            fontWeight: FontWeight.w600
                        ),),
                        GestureDetector(
                          onTap: (){
                            SmartDialog.dismiss();
                          },
                          child: Icon(Icons.close,size: 30.sp,color: Color(0xff999999),),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: 100.w,),
                  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                      getCameraPermission(context, (){
                        Navigator.of(context).pushNamed('ScanPage').then((val){
                          if(mounted){setState(() {});}
                        });
                      });
                    },
                    child: Container(
                      height: 84.w,
                      width: 654.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: themeColor,
                        borderRadius: BorderRadius.circular(8.w)
                      ),
                      child:Text('Scan Your Device'.tr,style: TextStyle(
                        color: Colors.white,
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w600
                      ),),
                    ),
                  ),
                  SizedBox(height: 32.w,),
                  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                      Navigator.of(context).pushNamed('MinAddDeviceInput').then((val){
                        print('base===' + baseDevice.toString());
                        setState(() {});
                      });
                    },
                    child: Container(
                      height: 84.w,
                      width: 654.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: Color(0xff2A2A2A),
                          borderRadius: BorderRadius.circular(8.w)
                      ),
                      child:Text('Manual Entry'.tr,style: TextStyle(
                          color: Colors.white,
                          fontSize: 28.sp,
                          fontWeight: FontWeight.w600
                      ),),
                    ),
                  ),
                ],
              ),
            );
          },alignment: Alignment.bottomCenter);
        }else if(index == 1){
          // _showNoNetworkAlert();
          Navigator.of(context).pushNamed('DeviceNetPage');
        }else if(index == 2){
          SmartDialog.show(builder: (ctx){
            return ConnectUsPage();
          },alignment: Alignment.bottomCenter);
        }

      },
      child: Container(
        margin: EdgeInsets.only(bottom: 48.w),
        height: 60.w,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              width: 32.w,
              height: 32.w,
              child: Image.asset(_items[index]['img']),
            ),
            SizedBox(width: 16.w,),
            Expanded(child: Container(
              child: Text(_items[index]['name'],style: TextStyle(
                  color: index !=3 ?Colors.white : Color(0xff999999),
                  fontSize: 28.sp
              ),),
            )),
            SizedBox(width: 2.w,),
            Visibility(child: Image.asset('assets/home/item_right.png',width: 40.w,),visible: index!=3,),
            Visibility(child: Text('$baseVersion',style: TextStyle(
              color: Colors.white,
              fontSize: 28.sp
            ),),visible: index==3,)

          ],
        ),
      ),
    );
  }

  connectItem(String text,String img,int type){
    return Container(
      width: 640.w,
      padding: EdgeInsets.all(32.w),
      decoration: BoxDecoration(
          color: Color(0xff3C3C3C),
          borderRadius: BorderRadius.circular(24.w)
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            child: Row(
              children: [
                Container(
                  width: 40.w,
                ),
                Expanded(child: Text(type==1?'Call number'.tr:'Send an email'.tr,style: TextStyle(
                  color: Colors.white,
                  fontSize: 32.sp,
                ),textAlign: TextAlign.center,)),
                Container(
                  width: 40.w,
                  child:  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Icon(Icons.close,size: 32.sp,color: Color(0xff999999),),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 90.w,),
          Container(
            height: 84.w,
            alignment: Alignment.center,
            // padding: EdgeInsets.symmetric(horizontal: 20.w),
            // decoration: BoxDecoration(
            //     color: Color(0xff494949),
            //     borderRadius: BorderRadius.circular(8.w)
            // ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Image.asset(img,width: 36.w,),
                // SizedBox(width: 24.w,),
                Text(text,style: TextStyle(
                    color: Colors.white,
                    fontSize: 50.sp
                ),)
              ],
            ),
          ),
          SizedBox(height: 108.w,),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // GestureDetector(
                //   onTap: (){
                //     SmartDialog.dismiss();
                //   },
                //   child: Container(
                //     child: Text('Cancel',style: TextStyle(
                //         color: Color(0xff666666),
                //         fontSize: 28.sp,
                //         fontWeight: FontWeight.w600
                //     ),),
                //     decoration: BoxDecoration(
                //         color: Color(0xffE8E8E8),
                //         borderRadius: BorderRadius.circular(84.w)
                //     ),
                //     width: 260.w,
                //     height: 92.w,
                //     alignment: Alignment.center,
                //   ),
                // ),
                // SizedBox(width: 32.w,),
                GestureDetector(
                  onTap: ()async{
                    SmartDialog.dismiss();
                    if(type == 1){
                      if(await canLaunchUrl(Uri.parse('tel:${feedbackInfo['spt.value.phone']['value']}'))){
                        launchUrl(Uri.parse('tel:${feedbackInfo['spt.value.phone']['value']}'));
                      }else{
                        await Clipboard.setData(ClipboardData(text: '${feedbackInfo['spt.value.phone']['value']}'));
                        showToast(connect_us_page_item_copy_success.tr);
                      }
                    }else{
                      if(await canLaunchUrl(Uri.parse('mailto:$text'))){
                        launchUrl(Uri.parse('mailto:$text'));
                      }else{
                        await Clipboard.setData(ClipboardData(text: text));
                        showToast(connect_us_page_item_copy_success.tr);
                      }
                    }
                  },
                  child: Container(
                    decoration: BoxDecoration(
                        color: Color(0xff3C55F8),
                        borderRadius: BorderRadius.circular(84.w)
                    ),
                    width: 260.w,
                    height: 92.w,
                    alignment: Alignment.center,
                    child: Text(type==1?'Call'.tr:'Send'.tr,style: TextStyle(
                        color: Colors.white,
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  _showNoNetworkAlert(){
    SmartDialog.show(builder: (ctx){
      return Container(
        height: 530.w,
        padding: EdgeInsets.only(left: 48.w,right: 48.w,top: 32.w,bottom: 48.w),
        decoration: BoxDecoration(
            color: Color(0xff1E1E1E),
            borderRadius: BorderRadius.only(topLeft: Radius.circular(32.w),topRight: Radius.circular(32.w))
        ),
        child: Column(
          children: [
            Container(
              child: Row(
                children: [
                  Text('Device Network Settings',style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),),
                  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Icon(Icons.close,size: 30.sp,color: Color(0xff999999),),
                  )
                ],
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
              ),
            ),
            SizedBox(height: 100.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                Navigator.of(context).pushNamed('DeviceNetPage').then((val){
                  setState(() {});
                });
              },
              child: Container(
                height: 84.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: themeColor,
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Select network',style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            SizedBox(height: 32.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                Navigator.of(context).pushNamed('DeviceNetPage').then((val){
                  setState(() {});
                });
              },
              child: Container(
                height: 84.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xff2A2A2A),
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Manual Entry'.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
          ],
        ),
      );
    },alignment: Alignment.bottomCenter);
    // SmartDialog.show(
    //     alignment: Alignment.center,
    //     builder: (BuildContext ctx){
    //       return Container(
    //         decoration: BoxDecoration(
    //             color: Colors.white,
    //             borderRadius: BorderRadius.circular(20.w)
    //         ),
    //         margin: EdgeInsets.symmetric(horizontal: 30.w),
    //         padding: EdgeInsets.symmetric(horizontal: 30.w,vertical: 30.w),
    //         child: Container(
    //           child: Column(
    //             mainAxisSize: MainAxisSize.min,
    //             children: [
    //               Container(
    //                 child: Text(alert_waring_title.tr),
    //               ),
    //               SizedBox(height: 30.w,),
    //               Container(
    //                 child: Text(home_have_no_network_alert_text.tr),
    //               ),
    //               SizedBox(height: 30.w,),
    //               Container(
    //                 child: Row(
    //                   mainAxisAlignment: MainAxisAlignment.spaceAround,
    //                   children: [
    //                     GestureDetector(
    //                       onTap: (){
    //                         SmartDialog.dismiss();
    //                       },
    //                       child: Container(
    //                         width: 200.w,
    //                         height: 90.w,
    //                         alignment: Alignment.center,
    //                         decoration: BoxDecoration(
    //                             color: Colors.grey,
    //                             borderRadius: BorderRadius.circular(20.w)
    //                         ),
    //                         child: Text(alert_waring_canclebtn_text.tr),
    //                       ),
    //                     ),
    //                     GestureDetector(
    //                       onTap: (){
    //                         SmartDialog.dismiss();
    //                         Navigator.of(context).pushNamed('DeviceNetPage').then((val){
    //                           // _homeViewSHow();
    //                           _getList();
    //                         });
    //                       },
    //                       child: Container(
    //                         width: 200.w,
    //                         height: 90.w,
    //                         alignment: Alignment.center,
    //                         decoration: BoxDecoration(
    //                             color: themeColor,
    //                             borderRadius: BorderRadius.circular(20.w)
    //                         ),
    //                         child: Text(alert_waring_surebtn_text.tr),
    //                       ),
    //                     )
    //                   ],
    //                 ),
    //               )
    //             ],
    //           ),
    //         ),
    //       );
    //     }
    // );
  }


}
